<template>
	<view class="content">
		<view style="width: 100%;height: 100vh;"/>
			<!-- <live-pusher id='livePusher' ref="livePusher" class="livePusher" url="rtmp://203.189.0.218/live1/2"
				mode="SD" :muted="true" :enable-mic="audio" :enable-camera="video" :auto-focus="true" :beauty="1" whiteness="2"></live-pusher> -->
		</view>
		<cover-view style="position: fixed;z-index: 9999;bottom: 150rpx;left: 0rpx;width: 100%;display: flex;justify-content: center;">
			<cover-image @click="initid" :props="rtcprop" :change:props="rtc.init" src="/static/images/icon_guad.png" style="width: 120rpx;height: 120rpx;"></cover-image>
			<cover-image @click="initid1" src="/static/images/icon_guad.png" style="width: 120rpx;height: 120rpx;"></cover-image>
			<cover-image @click="rtc.unpublish" src="/static/images/icon_guad.png" style="width: 120rpx;height: 120rpx;"></cover-image>
		</cover-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				context:null,
  				video:true,
				id:0,
				rtcprop:{
					id:0
				}
			}
		},
		onReady() {
		    // 注意：需要在onReady中 或 onLoad 延时
		    // this.context = uni.createLivePusherContext("livePusher", this);
			// this.start()
		},
		methods: {
			initid:function(){
				this.rtcprop = {
					id: 456 + Math.random(),
					videoType:"user"
				}
			},
			initid1:function(){
				this.rtcprop = {
					id: 456 + Math.random(),
					videoType:"environment"
				}
			},
			cesdataa:function(rtcdata){
				console.log(`收到的信息`,rtcdata)
				setTimeout(()=>{
					rtcdata.unpublish()
				},5000)
			},
			start: function() {
				this.context.start({
					success: (a) => {
						console.log("livePusher.start:" + JSON.stringify(a));
					}
				});
			},
			close: function() {
				
				// this.context.stop({
				// 	success: (a) => {
				// 		console.log("livePusher.close:" + JSON.stringify(a));
				// 		uni.navigateBack()
				// 	}
				// });
			},
		}
	}
</script>
<!-- lang="renderjs" -->
<script module="rtc" lang="renderjs">
	let data = {
		userRct:''
	}
	export default {
		data(){
			return {
				
			}
		},
		mounted() {
			// this.init({
			// 		audio:true,
			// 		video:true,
			// 		id:123
			// 	})
		},
		methods: {
			unpublish:function(){
				console.log(3344,data.userRct)
				data.userRct.unpublish()
			},
			init:async function(optionsa, oldValue, ownerVm, vm){
				if(optionsa.id == 0){
					return
				}
				console.log(112233,optionsa,this.data)
				let options =  {
					audio:true,
					video:true,
					id:Math.floor(optionsa.id),
					facingMode:optionsa.videoType ?? "user"
				}
				const roomId = "videocall"
				const id = options.id
				const pc = new RTCPeerConnection(null);
				pc.addTransceiver('audio', {
					direction: 'sendonly'
				});
				pc.addTransceiver('video', {
					direction: 'sendonly'
				});
				const stream = await navigator.mediaDevices.getUserMedia({
					audio: true,
					video: {
						facingMode: options.facingMode
					},
				});
				console.log(stream);
				stream.getTracks().forEach(function(track) {
					pc.addTrack(track);
					if (track.kind === 'audio') {
						if (options.audio === false) {
							track.enabled = false;
						}
					}
					if (track.kind === 'video') {
						if (options.video === false) {
							track.enabled = false;
						}
					}
				});
				let offer = await pc.createOffer();
				await pc.setLocalDescription(offer);
				let session = await new Promise(function(resolve, reject) {
					// @see https://github.com/rtcdn/rtcdn-draft
					let data = {
						api: `https://dx11.haoleen.com/rtc/v1/publish/`,
						tid: id,
						streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
						clientip: null,
						sdp: offer.sdp,
					};
					console.log('Generated offer: ', data);
				
					const xhr = new XMLHttpRequest();
					xhr.onload = function() {
						if (xhr.readyState !== xhr.DONE) return;
						if (xhr.status !== 200) return reject(xhr);
						const data = JSON.parse(xhr.responseText);
						console.log('Got answer: ', data);
						if (data.code === 400) {
							resolve(false);
						}
						return data.code ? reject(xhr) : resolve(data);
					};
					xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
					xhr.setRequestHeader('Content-type', 'application/json');
					xhr.send(JSON.stringify(data));
				});
				console.log(session);
				if (session === false) {
					return false;
				}
				await pc.setRemoteDescription(
					new RTCSessionDescription({
						type: 'answer',
						sdp: session.sdp
					}),
				);
				
				function muteAudio(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'audio') {
							track.enabled = type ?? false;
						}
					});
				}
				
				function muteVideo(type) {
					stream.getTracks().forEach(function(track) {
						if (track.kind === 'video') {
							track.enabled = type ?? false;
						}
					});
				}
				async function unpublish() {
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					pc.close();
					// const cid = await getPublishCidById(options.roomId, options.id);
					// console.log(cid);
					// const ret = await axios.delete(
					//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
					// );
				}
				
				// const userinfo = uni.getStorageSync("user")
				
				data.userRct = {
					id: id,
					name: name,
					roomId: roomId,
					pc,
					stream,
					audio: true,
					video: true,
					muteAudio,
					muteVideo,
					unpublish: unpublish,
				};
				
				console.log(88991,data.userRct)
				// const ret = await srs.publishStream({
				// 	roomId:'videocall',
				// 	id:11
				// })
				// consle.log(88991,ret)
			}
		}
	}
</script>

<style scoped>
	.content{
		width: 100%;
	}
	.livePusher{
		width: 100%;
		height: 100vh;
	}
</style>